/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mahumLogs.beans;

import com.mahumLogs.backedbeans.Administrateur;
import com.mahumLogs.backedbeans.Etudiant;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Default;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Adrien
 */
@Named
@RequestScoped
public class LoginBean {

    @PersistenceContext
    private EntityManager em;

    
    private @Inject SessionBean sessionBean;
    
    private @Inject ConfigurationBean confBean;

    private String login;
    private String password;

    /**
     * Constructeur
     */
    public LoginBean() {

    }

    /**
     * Fonction qui permet de connecter un étudiant ou un administrateur
     *
     * @throws IOException
     */
    public void connection() throws IOException {
        System.out.println("Connexion");
        MessageDigest m;
        try {
            m = MessageDigest.getInstance("MD5");
            m.update(this.password.getBytes("UTF8"));
            byte s[] = m.digest();
            String result = "";

            for (int i = 0; i < s.length; i++) {
                result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
            }
            List<Administrateur> listAdmin = em.createQuery("SELECT e FROM Administrateur e WHERE e.login = '" + this.login + "' AND e.password = '" + result + "'").getResultList();
            if (!listAdmin.isEmpty()) {
                sessionBean.setAdmin(listAdmin.get(0));
                sessionBean.setEtudiant(null);
                sessionBean.setIsLogged(true);
                FacesContext.getCurrentInstance().getExternalContext().redirect("/MahumLogs_Production/admin/index.jsf");
            } else {

                List<Etudiant> listEtudiant = em.createQuery("SELECT e FROM Etudiant e WHERE e.login = '" + this.login + "' AND e.password = '" + result + "'").getResultList();
                if (!listEtudiant.isEmpty()) {
                    sessionBean.setAdmin(null);
                    sessionBean.setEtudiant(listEtudiant.get(0));
                    sessionBean.setIsLogged(true);
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/MahumLogs_Production/user/gererMachines.jsf");
                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erreur", "Nom d'utilisateur ou mot de passe incorrect."));
                }

            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Fonction qui permet de déconnecter un étudiant ou un administrateur
     *
     * @throws IOException
     */
    public void deconnexion() throws IOException {
        ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true)).invalidate();
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        sessionBean.setIsLogged(false);
        redirect();
    }

    /**
     * Fonction qui redirige un utilisateur
     *
     * @throws IOException
     */
    public void redirect() throws IOException {
        if (!sessionBean.isIsLogged()){
            HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            if(!request.getRequestURI().equals(request.getContextPath()+"/")){
                FacesContext.getCurrentInstance().getExternalContext().redirect("/MahumLogs_Production");
            }
        }
    }

    /**
     * Fonction qui redirige un utilisateur après être connecté
     *
     * @throws IOException
     */
    public void redirectLogin() throws IOException {
        if (!sessionBean.isIsLogged()) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("/MahumLogs_Production/");
        }
    }

    /**
     * @return em
     */
    public EntityManager getEm() {
        return em;
    }

    /**
     * @param em
     */
    public void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * @return sessionBean
     */
    public SessionBean getSessionBean() {
        return sessionBean;
    }

    /**
     * @param sessionBean
     */
    public void setSessionBean(SessionBean sessionBean) {
        this.sessionBean = sessionBean;
    }

    /**
     * @return login
     */
    public String getLogin() {
        return login;
    }

    /**
     * @param login
     */
    public void setLogin(String login) {
        this.login = login;
    }

    /**
     * @return password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
    }
}
